package com.simple.core.validate;

import com.simple.annotation.validate.Validate;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.Set;

/**
 * 参数校验，支持@Validate标记的函数
 *
 * @author FanXing
 * @date 2023年02月12日 16:37
 */
@Aspect
@Component
public class ValidateAspect {
    @Autowired
    private Validator validator;

    @Before("@annotation(validate) ")
    public void validateParams(JoinPoint point, Validate validate) {
        for (Object obj : point.getArgs()) {
            Set<ConstraintViolation<Object>> violations = validator.validate(obj, validate.value());

            if (!violations.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (ConstraintViolation<?> constraintViolation : violations) {
                    sb.append(constraintViolation.getMessage());
                }
                throw new ConstraintViolationException(sb.toString(), violations);
            }
        }
    }
}
